import {defineStore} from "pinia"
import {ref,reactive,computed,watchEffect} from 'vue'


export const useShoppingCartStore = defineStore('shoppingCart',() => {
  const goodList = ref([])
  const goodCount = computed(() => {
    return goodList.value.reduce((pre,cur) =>  pre + cur.buyNumber ,0)
  })
  const totalPrice = computed(() => {
    //todo: 数学元算的浮点数误差问题
    return goodList.value.reduce((pre,cur) => pre + cur.price * cur.buyNumber,0)
  })

  
  function addGood(goodInfo){
    const exsitGood = goodList.value.find(item => item.id === goodInfo.id)
    if(exsitGood){
      exsitGood.buyNumber += 1
      return
    }
    goodInfo.buyNumber = 1
    goodList.value.push(goodInfo)
  }

  function removeGood(){

  }

  function clearCart(){
    goodList.value = []
  }

  return {
    goodList,
    totalPrice,
    addGood,
    removeGood,
    goodCount,
    clearCart
  }
})